package cn.ivicar.oss.controller;

import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.ibatis.model.BaseExample;
import cn.com.carsmart.ws.model.*;
import cn.com.carsmart.ws.service.*;
import cn.ivicar.oss.entity.ResponseEntity;
import cn.ivicar.oss.util.JsonUtils;
import cn.ivicar.redis.JedisClusterFactory;
import com.google.inject.Inject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import redis.clients.jedis.JedisCluster;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/5/16.
 */
public class VehicleController {

    private static final String IOV_SHADOW_GPS = "iov:shadow:gps:";

    @Inject
    private VehicleManager vehicleManager;
    @Inject
    private SimFlowInfoManager simFlowInfoManager;
    @Inject
    private VehicleSimManager vehicleSimManager;
    @Inject
    private CustomerVehicleManager customerVehicleManager;
    @Inject
    private SimInfoManager simInfoManager;
    @Inject
    private CustomerManager customerManager;

    public JSONObject getVehicleByPlate(String licensePlate) throws CarsmartException {
        if (StringUtils.isNotBlank(licensePlate)) {
            BaseExample example = this.vehicleManager.getExample();
            example.or().andPropertyEqualTo(licensePlate, "licensePlate");
            List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
            if (vehicles != null && vehicles.size() > 0) {
                JSONObject jsonObject = JsonUtils.getVehicleJSON(vehicles.get(0));
                return jsonObject;
            }
        }

        return null;
    }

    public JSONObject getVehicleBySerial(String serial) throws CarsmartException {
        BaseExample example = this.vehicleManager.getExample();
        example.or().andPropertyEqualTo(serial, "serial");
        List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
        if (vehicles != null && vehicles.size() > 0) {
            JSONObject vehicleJSON = JsonUtils.getVehicleJSON(vehicles.get(0));
            return vehicleJSON;
        }

        return null;
    }

    public JSONObject getVehicleById(Long id) throws CarsmartException {

        BaseExample example = this.vehicleManager.getExample();
        example.or().andPropertyEqualTo(id, "id");
        List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
        if (vehicles != null && vehicles.size() > 0) {
            JSONObject vehicleJSON = JsonUtils.getVehicleJSON(vehicles.get(0));
            return vehicleJSON;
        }

        return null;
    }

    //分页查询车信息
    public JSONArray getVehicleList() throws CarsmartException {
        JSONArray jsonArray = new JSONArray();
        List<Vehicle> vehicles = this.vehicleManager.list();
        if (vehicles != null && vehicles.size() > 0) {
            for (Vehicle v : vehicles) {
                JSONObject vehicleJSON = JsonUtils.getVehicleJSON(v);
                jsonArray.add(vehicleJSON);
            }
        }

        return jsonArray;
    }

    public String getSimIccidByVid(Long vid) throws CarsmartException {
        BaseExample example = this.vehicleSimManager.getExample();
        example.or().andPropertyEqualTo(vid, "vehicleId").andPropertyEqualTo(1, "status");
        List<VehicleSim> vehicleSims = this.vehicleSimManager.listByBaseExample(example);
        if (vehicleSims != null && vehicleSims.size() > 0) {
            return vehicleSims.get(0).getIccid();
        }

        return null;
    }

    public Long getCustomerIdByVid(Long vid) throws CarsmartException {
        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(vid, "vehicleId").andPropertyEqualTo(1, "owner")
            .andPropertyEqualTo(1, "status");
        List<CustomerVehicle> customerVehicles =
            this.customerVehicleManager.listByBaseExample(example);
        if (customerVehicles != null && customerVehicles.size() > 0) {
            return customerVehicles.get(0).getCustomerId();
        }

        return null;
    }

    public ResponseEntity updateVehicle(JSONObject obj) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (obj.isNullObject() || obj.isEmpty()) {
            responseEntity.setCode(400);
            responseEntity.setMessage("请求参数不能为空！");
            return responseEntity;
        }

        long vid = obj.optLong("vid");
        BaseExample example = vehicleManager.getExample();
        example.or().andPropertyEqualTo(vid, "id");
        List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
        if (vehicles != null && vehicles.size() > 0) {
            Vehicle update = vehicles.get(0);
            if (obj.containsKey("name")) {
                String name = obj.optString("name", "").trim();
                update.setName(name);
            }

            if (obj.containsKey("serial")) {
                String serial = obj.optString("serial", "").trim();
                update.setSerial(serial);
            }

            if (obj.containsKey("plate")) {
                String plate = obj.optString("plate", "").trim();
                update.setLicensePlate(plate.toUpperCase());
            }
            if (obj.containsKey("vin")) {
                String vin = obj.optString("vin", "").trim();
                update.setVin(vin);
            }
            if (obj.containsKey("ein")) {
                String ein = obj.optString("ein", "").trim();
                update.setEin(ein);
            }
            update.setUpdated(new Date());

            this.vehicleManager.update(update);
            responseEntity.setDataObject(update);
            return responseEntity;
        }

        responseEntity.setCode(400);
        responseEntity.setMessage("更新失败！车辆信息不存在！");
        return responseEntity;

    }

    public ResponseEntity addVehicle(JSONObject obj) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (obj.isNullObject() || obj.isEmpty()) {
            responseEntity.setCode(400);
            responseEntity.setMessage("请求参数不能为空！");
            return responseEntity;
        }
        Vehicle vehicle = new Vehicle();

        if (obj.containsKey("name")) {
            String name = obj.optString("name", "").trim();
            vehicle.setName(name);
        }

        if (obj.containsKey("serial")) {
            String serial = obj.optString("serial", "").trim();
            BaseExample example = vehicleManager.getExample();
            example.or().andPropertyEqualTo(serial, "serial");
            int i = this.vehicleManager.countByExample(example);
            if (i > 0) {
                responseEntity.setCode(400);
                responseEntity.setMessage("新增失败！该设备号已存在！");
                return responseEntity;
            }
            vehicle.setSerial(serial);
        }

        if (obj.containsKey("plate")) {
            String plate = obj.optString("plate", "").trim();
            vehicle.setLicensePlate(plate.toUpperCase());
        }
        if (obj.containsKey("vin")) {
            String vin = obj.optString("vin", "").trim();
            vehicle.setVin(vin);
        }
        if (obj.containsKey("ein")) {
            String ein = obj.optString("ein", "").trim();
            vehicle.setEin(ein);
        }
        vehicle.setCreated(new Date());
        vehicle.setUpdated(new Date());

        this.vehicleManager.insert(vehicle);
        return responseEntity;
    }

    public ResponseEntity deleteVehicle(String id) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();
        if (StringUtils.isBlank(id)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取车辆标识!");
            return responseEntity;
        }

        long vid = Long.parseLong(id);
        BaseExample example = this.vehicleSimManager.getExample();
        example.or().andPropertyEqualTo(vid, "vehicleId").andPropertyEqualTo(1, "status");
        int count = this.vehicleSimManager.countByExample(example);
        if (count > 0) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败，请先解除车卡关系！");
            return responseEntity;
        }

        BaseExample cvExample = this.customerVehicleManager.getExample();
        cvExample.or().andPropertyEqualTo(vid, "vehicleId").andPropertyEqualTo(1, "status");
        int cvCount = this.customerVehicleManager.countByExample(cvExample);
        if (cvCount > 0) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败，请先解除人车关系！");
            return responseEntity;
        }

        this.vehicleManager.deleteByPrimaryKey(Long.parseLong(id));
        return responseEntity;
    }

    public ResponseEntity deleteVehicleCustomerRel(String vidStr,
        String cidStr) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();

        if (StringUtils.isBlank(vidStr)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取车辆标识!");
            return responseEntity;
        }

        if (StringUtils.isBlank(cidStr)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取用户标识!");
            return responseEntity;
        }

        long vid = Long.parseLong(vidStr);
        long cid = Long.parseLong(cidStr);
        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(vid, "vehicleId").andPropertyEqualTo(cid, "customerId")
            .andPropertyEqualTo(1, "status");
        List<CustomerVehicle> customerVehicles =
            this.customerVehicleManager.listByBaseExample(example);
        if (customerVehicles != null && customerVehicles.size() > 0) {
            CustomerVehicle customerVehicle = customerVehicles.get(0);
            customerVehicle.setStatus(0);
            customerVehicle.setUpdated(new Date());
            this.customerVehicleManager.update(customerVehicle);
            return responseEntity;
        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败，人车关系不存在！");
            return responseEntity;
        }
    }

    public ResponseEntity deleteVehicleSimRel(String vidStr,
        String iccid) throws CarsmartException {

        ResponseEntity responseEntity = new ResponseEntity();

        if (StringUtils.isBlank(vidStr)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取车辆标识!");
            return responseEntity;
        }
        if (StringUtils.isBlank(iccid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败！未获取sim卡标识!");
            return responseEntity;
        }

        long vid = Long.parseLong(vidStr);
        BaseExample example = this.vehicleSimManager.getExample();
        example.or().andPropertyEqualTo(vid, "vehicleId").andPropertyEqualTo(iccid, "iccid")
            .andPropertyEqualTo(1, "status");
        List<VehicleSim> vehicleSims = this.vehicleSimManager.listByBaseExample(example);
        if (vehicleSims != null && vehicleSims.size() > 0) {
            VehicleSim vehicleSim = vehicleSims.get(0);
            vehicleSim.setStatus(0);
            vehicleSim.setUpdated(new Date());
            this.vehicleSimManager.update(vehicleSim);
            return responseEntity;
        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("删除失败，车卡关系不存在！");
            return responseEntity;
        }
    }

    public ResponseEntity getCurrentPosition(String vid) throws CarsmartException {

        //***查数据库对应关系

        ResponseEntity responseEntity = new ResponseEntity();

        if (StringUtils.isBlank(vid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("获取位置失败！参数为空！");
            return responseEntity;
        }
        long vechicleId = Long.parseLong(vid);
        BaseExample example = this.vehicleManager.getExample();
        example.or().andPropertyEqualTo(vechicleId, "id");
        List<Vehicle> vehicles = this.vehicleManager.listByBaseExample(example);
        if (vehicles != null && vehicles.size() > 0) {
            String serial = vehicles.get(0).getSerial();
            JedisCluster cluster = JedisClusterFactory.getDefaultJedisCluster();
            String shadowStr = cluster.get(IOV_SHADOW_GPS + serial);
            if (StringUtils.isNotBlank(shadowStr)) {
                JSONObject shadow = JSONObject.fromObject(shadowStr);
                String lat = shadow.optString("amapLat", null);
                String lng = shadow.optString("amapLng", null);
                if (StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lng)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("lat", lat);
                    jsonObject.put("lng", lng);
                    responseEntity.setDataObject(jsonObject);
                    return responseEntity;
                } else {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("获取位置失败！未查询到车辆位置！");
                    return responseEntity;
                }
            } else {
                responseEntity.setCode(400);
                responseEntity.setMessage("获取位置失败！未查询到车辆位置！");
                return responseEntity;
            }
        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("获取位置失败！未查询到车辆位置！");
            return responseEntity;
        }

        //临时逻辑
        /*BaseExample example = this.vehicleStateManager.getExample();
        example.or().andPropertyEqualTo(vechicleId,"vehicleId");
        List<VehicleState> vehicleStates = this.vehicleStateManager.listByBaseExample(example);
        if(vehicleStates!= null && vehicleStates.size()>0){
            VehicleState vehicleState = vehicleStates.get(0);
            String latitude = vehicleState.getLatitude().toString();
            String longitude = vehicleState.getLongitude().toString();
            if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("lat", latitude);
                jsonObject.put("lng", longitude);
                responseEntity.setDataObject(jsonObject);
                return responseEntity;
            } else {
                responseEntity.setCode(400);
                responseEntity.setMessage("获取位置失败！未查询到车辆位置！");
                return responseEntity;
            }
        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("获取位置失败！未查询到车辆位置！");
            return responseEntity;
        }*/

        //
    }


    public JSONArray getCustomers(String id) throws CarsmartException {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        BaseExample example = this.customerVehicleManager.getExample();
        example.or().andPropertyEqualTo(Long.parseLong(id), "vehicleId")
            .andPropertyEqualTo(1, "status");
        List<CustomerVehicle> customerVehicles =
            this.customerVehicleManager.listByBaseExample(example);
        if (customerVehicles != null && customerVehicles.size() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (CustomerVehicle cv : customerVehicles) {
                JSONObject customerObj = getCustomerById(cv.getCustomerId());
                if (customerObj != null) {
                    if (cv.getOwner()) {
                        customerObj.put("relation", "绑定关系");
                    } else {
                        customerObj.put("relation", "分享关系");
                    }
                    //增加绑定时间
                    Date create = cv.getCreated();
                    String createStr = sdf.format(create);
                    customerObj.put("bindTime", createStr);

                    jsonArray.add(customerObj);
                }
            }
        }

        return jsonArray;
    }

    public JSONObject getCustomerById(Long id) throws CarsmartException {

        BaseExample example = this.customerManager.getExample();
        example.or().andPropertyEqualTo(id, "id");
        List<Customer> customers = this.customerManager.listByBaseExample(example);
        if (customers != null && customers.size() > 0) {
            JSONObject customerJSON = JsonUtils.getCustomerJSON(customers.get(0));
            return customerJSON;
        }

        return null;
    }

    public JSONArray getSims(String id) throws CarsmartException {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        JSONArray jsonArray = new JSONArray();
        BaseExample example = this.vehicleSimManager.getExample();
        example.or().andPropertyEqualTo(Long.parseLong(id), "vehicleId")
            .andPropertyEqualTo(1, "status");
        List<VehicleSim> vehicleSims = this.vehicleSimManager.listByBaseExample(example);
        if (vehicleSims != null && vehicleSims.size() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (VehicleSim vs : vehicleSims) {
                JSONObject simInfoObj = getSimInfoByIccid(vs.getIccid());
                if (simInfoObj != null) {
                    //增加绑定时间
                    Date create = vs.getCreated();
                    String createStr = sdf.format(create);
                    simInfoObj.put("bindTime", createStr);
                    jsonArray.add(simInfoObj);
                }
            }
        }

        return jsonArray;
    }

    public JSONObject getSimInfoByIccid(String iccid) throws CarsmartException {

        BaseExample example = this.simInfoManager.getExample();
        example.or().andPropertyEqualTo(iccid, "iccid");
        List<SimInfo> simInfos = this.simInfoManager.listByBaseExample(example);
        if (simInfos != null && simInfos.size() > 0) {
            JSONObject simInfoJSON = JsonUtils.getSimInfoJSON(simInfos.get(0));

            simInfoJSON.put("combo","包月");//套餐类型
            simInfoJSON.put("flowSum",0);//流量总量
            simInfoJSON.put("flowMoney",0);//流量花费

            BaseExample example1 = this.simFlowInfoManager.getExample();
            example1.or().andPropertyEqualTo(simInfos.get(0).getIccid(),"iccid");
            List<SimFlowInfo> simFlowInfos =
                this.simFlowInfoManager.listByBaseExample(example1);
            if(simFlowInfos != null && simFlowInfos.size()>0){
                SimFlowInfo simFlowInfo = simFlowInfos.get(simFlowInfos.size() - 1);
                simInfoJSON.put("combo",simFlowInfo.getFlowPack());//套餐类型
                simInfoJSON.put("flowSum",simFlowInfo.getFlowAmount());//流量总量
                simInfoJSON.put("flowMoney",simFlowInfo.getFlowUsed());//流量花费
            }
            return simInfoJSON;
        }

        return null;
    }

    public ResponseEntity addCustomerRel(JSONObject jsonObject) throws CarsmartException {
        ResponseEntity responseEntity = new ResponseEntity();
        if (null == jsonObject) {
            responseEntity.setCode(400);
            responseEntity.setMessage("参数异常!对象为空！");
            return responseEntity;
        }

        String vid = jsonObject.getString("vid");
        if (StringUtils.isBlank(vid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("未获取客户标识!");
            return responseEntity;
        }

        String value = jsonObject.getString("value");
        if (StringUtils.isBlank(value)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("手机号不能为空!");
            return responseEntity;
        }

        String relaType = jsonObject.optString("relaType", "0");
        BaseExample example = this.customerManager.getExample();
        example.or().andPropertyEqualTo(value, "mobile");
        List<Customer> customers = this.customerManager.listByBaseExample(example);
        if (customers != null && customers.size() > 0) {
            Long id = customers.get(0).getId();
            //如果想增加绑定关系，则先判断车辆是否已经存在绑定关系
            if ("1".equalsIgnoreCase(relaType)) {
                BaseExample example1 = this.customerVehicleManager.getExample();
                example1.or().andPropertyEqualTo(vid, "vehicleId")
                    .andPropertyEqualTo(true, "owner");
                int i = this.customerVehicleManager.countByExample(example1);
                if (i > 0) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("绑定失败！该车辆已存在绑定关系!");
                    return responseEntity;
                }
            }

            //表中已经存在删除状态的人车关系，防止插入失败，更新状态
            BaseExample example1 = this.customerVehicleManager.getExample();
            example1.or().andPropertyEqualTo(Long.parseLong(vid), "vehicleId")
                .andPropertyEqualTo(id, "customerId");
            List<CustomerVehicle> customerVehicles =
                this.customerVehicleManager.listByBaseExample(example1);
            if (customerVehicles != null && customerVehicles.size() > 0) {
                CustomerVehicle customerVehicle = customerVehicles.get(0);
                customerVehicle.setStatus(1);
                customerVehicle.setOwner("1".equalsIgnoreCase(relaType) ? true : false);
                customerVehicle.setCreated(new Date());
                customerVehicle.setUpdated(new Date());
                this.customerVehicleManager.updateSelective(customerVehicle);
                return responseEntity;

            } else {
                CustomerVehicle customerVehicle = new CustomerVehicle();
                customerVehicle.setCustomerId(id);
                customerVehicle.setVehicleId(Long.parseLong(vid));
                customerVehicle.setStatus(1);
                customerVehicle.setOwner("1".equalsIgnoreCase(relaType) ? true : false);
                customerVehicle.setCreated(new Date());
                customerVehicle.setUpdated(new Date());
                try {
                    this.customerVehicleManager.insert(customerVehicle);
                    return responseEntity;
                } catch (Exception e) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("关系已存在，重复添加!");
                    return responseEntity;
                }
            }
        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("客户不存在!");
            return responseEntity;
        }
    }

    public ResponseEntity addSimRel(JSONObject jsonObject) throws CarsmartException {
        ResponseEntity responseEntity = new ResponseEntity();
        if (null == jsonObject) {
            responseEntity.setCode(400);
            responseEntity.setMessage("参数异常!对象为空！");
            return responseEntity;
        }

        String vid = jsonObject.getString("vid");
        if (StringUtils.isBlank(vid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("未获取客户标识!");
            return responseEntity;
        }

        String iccid = jsonObject.getString("iccid");
        if (StringUtils.isBlank(iccid)) {
            responseEntity.setCode(400);
            responseEntity.setMessage("sim卡的iccid不能为空!");
            return responseEntity;
        }

        BaseExample example = this.simInfoManager.getExample();
        example.or().andPropertyEqualTo(iccid, "iccid");
        List<SimInfo> simInfos = this.simInfoManager.listByBaseExample(example);
        if (simInfos != null && simInfos.size() > 0) {

            //表中已经存在vid和iccid的已删除状态的绑定关系，防止插入失败，更新状态
            BaseExample example1 = this.vehicleSimManager.getExample();
            example1.or().andPropertyEqualTo(Long.parseLong(vid), "vehicleId")
                .andPropertyEqualTo(iccid, "iccid");
            List<VehicleSim> vehicleSims = this.vehicleSimManager.listByBaseExample(example1);
            if (vehicleSims != null && vehicleSims.size() > 0) {
                VehicleSim vehicleSim = vehicleSims.get(0);
                vehicleSim.setStatus(1);
                vehicleSim.setCreated(new Date());
                vehicleSim.setUpdated(new Date());
                this.vehicleSimManager.updateSelective(vehicleSim);
                return responseEntity;
            } else {
                VehicleSim customerVehicle = new VehicleSim();
                customerVehicle.setVehicleId(Long.parseLong(vid));
                customerVehicle.setIccid(iccid);
                customerVehicle.setStatus(1);
                customerVehicle.setCreated(new Date());
                customerVehicle.setUpdated(new Date());
                try {
                    this.vehicleSimManager.insert(customerVehicle);
                    return responseEntity;
                } catch (Exception e) {
                    responseEntity.setCode(400);
                    responseEntity.setMessage("关系已存在，重复添加!");
                    return responseEntity;
                }
            }

        } else {
            responseEntity.setCode(400);
            responseEntity.setMessage("sim卡不存在!");
            return responseEntity;
        }
    }

}
